package com.netprovider.user.service.baseinfo.dao;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.netprovider.user.service.baseinfo.objects.User;
import com.netprovider.user.service.baseinfo.util.DataLoader;
import com.netprovider.user.service.baseinfo.util.DateConverter;

public class UserDAO {
	
	static {
		try {
			DataLoader.loadUserData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static User searchUser(String userId) {
		List<User> userList = DataLoader.getUserData();
		for (User user : userList) {
			if (user.getUserId().equals(userId)) {
				return user;
			}
		}
		return null;
	}
	
	public static void addUser(User user) {
		DataLoader.getUserData().add(user);
	}
	
	public static void deleteUser(String userId) {
		List<User> userList = DataLoader.getUserData();
		for (User user : userList) {
			if (user.getUserId().equals(userId)) {
				userList.remove(user);
			}
		}
	}
	
	public static void updateUser(User user) {
		List<User> userList = DataLoader.getUserData();
		for (int i=0 ; i < userList.size() ; i++) {
			User aUser = userList.get(i);
			if (aUser.getUserId().equals(user.getUserId())) {
				userList.set(i, user);
			}
		}
	}
	
	public static List<User> getUsersByRegDate(String strStartDate,String strEndDate) throws Exception {
		DateConverter dc = new DateConverter();
		Date startDate = dc.unmarshal(strStartDate);
		Date endDate = dc.unmarshal(strEndDate);
		List<User> userList = DataLoader.getUserData();
		List<User> suitableUserList = new ArrayList<User>();
		for (User user : userList) {
			if (user.getRegisterDate().after(startDate) 
					&& user.getRegisterDate().before(endDate)){
				suitableUserList.add(user);
			}
		}
		return suitableUserList;
	}
	
	
}
